package aidturith.ihm.component;

import java.awt.event.KeyEvent;
import java.util.regex.PatternSyntaxException;

import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;

import aidturith.Constant;
import aidturith.ihm.action.key.EscapeAction;
import aidturith.ihm.panel.proto.TablePanel;

public class FilterTextField extends JTextField {

	private static final long serialVersionUID = 1L;

	private TablePanel panel;

	public FilterTextField(TablePanel panel) {
		super();

		this.panel = panel;

		setPreferredSize(Constant.FIELD_SIZE);

		getDocument().addDocumentListener(new DocumentListener() {
			@Override
			public void changedUpdate(DocumentEvent e) {
				newFilter(getText());
			}

			@Override
			public void removeUpdate(DocumentEvent e) {
				newFilter(getText());
			}

			@Override
			public void insertUpdate(DocumentEvent e) {
				newFilter(getText());
			}
		});

		KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
		getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(escape, "Escape");
		getActionMap().put("Escape", new EscapeAction(this));
	}

	/**
	 * Filtre les logs.
	 */
	public void newFilter(String text) {
		RowFilter<DefaultTableModel, Object> rf = null;
		try {
			rf = RowFilter.regexFilter("(?i)"+text);
		} catch (PatternSyntaxException e) {
			return;
		}
		panel.getSorter().setRowFilter(rf);
		panel.clearSelection();
	}

	public void clearFilter() {
		newFilter("");
		setText("");
	}

}
